package com.linciping.useges.plugin.action;

import com.intellij.find.SearchInBackgroundOption;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.linciping.useges.plugin.asyc.ModuleSourceUsegesThread;
import com.linciping.useges.plugin.util.CollectionUtil;
import com.linciping.useges.plugin.util.ProjectFileUtil;
import com.linciping.useges.plugin.util.Util;
import org.jetbrains.annotations.NotNull;

import java.util.List;
import java.util.Locale;

public class ModuleSourceUsegesAction extends BaseUsegesAction {

    @Override
    public void actionPerformed(AnActionEvent e) {
        Project project = e.getProject();
        Module targetModule = e.getData(LangDataKeys.MODULE);
        assert project != null;
        assert targetModule != null;
        List<VirtualFile> targetModuleSourceFileList = ProjectFileUtil.getModuleSourceList(targetModule, false, true);
        if (CollectionUtil.isListEmpty(targetModuleSourceFileList)) {
            return;
        }
        String title = String.format(Locale.getDefault(), "search %s", targetModule.getName());
        Task.Backgroundable task = new Task.Backgroundable(project, title, true, new SearchInBackgroundOption()) {
            @Override
            public void run(@NotNull ProgressIndicator indicator) {
                new ModuleSourceUsegesThread(project, targetModule, targetModuleSourceFileList).run();
            }

            @NotNull
            @Override
            public NotificationInfo getNotificationInfo() {
                return new NotificationInfo("Search Usages",
                        "Module Source Useges", "Search...");
            }
        };
        ProgressManager.getInstance().run(task);
    }


    @Override
    protected boolean canUpdate(AnActionEvent e) {
        return Util.hasModule(e);
    }
}
